#!/bin/bash

USERNAME="root"
DEST_PATH="/root"
IP_FILE="ip_addr.txt"

# 检查是否安装了 sshpass
if ! command -v sshpass &> /dev/null
then
    echo "正在安装 sshpass"
    yum -y install sshpass
fi

# 检查是否传入了文件名参数
if [ $# -eq 0 ]; then
  echo "没有输入需要传输的文件"
  echo "Usage: $0 <filename1> <filename2> ... <filenameN>"
  exit 1
fi

# 检查IP文件是否存在
if [ ! -f "$IP_FILE" ]; then
  echo "File $IP_FILE does not exist."
  read -p "IP文件不存在。是否从远程仓库下载？(y/n): " download_choice
  if [ "$download_choice" = "y" ]; then
    wget https://gitee.com/michelalive/shell_scripts/raw/master/system/ip_addr.txt -O $IP_FILE
    if [ $? -ne 0 ]; then
      echo "下载失败。请检查网络连接或远程仓库地址。"
      exit 1
    fi
    echo >> $IP_FILE
  else
    echo "没有IP文件。脚本退出。"
    exit 1
  fi
fi

# 读取IP列表
IP_LIST=()
while IFS= read -r line
do
  if [ -n "$line" ]; then
    IP_LIST+=("$line")
  fi
done < "$IP_FILE"

# 定义密码变量
password=""

# 传送文件到每一台机器
for FILE in "$@"
do
  # 检查文件是否存在
  if [ -f "$FILE" ]; then
    echo "File $FILE 是一个文件."
  elif [ -d "$FILE" ]; then
    echo "$FILE 是一个目录."
  else
    echo "$FILE 也不是一个目录."
    echo "传输中断"
    exit 1
  fi

  for IP in "${IP_LIST[@]}"
  do
    echo "Transferring $FILE to $IP..."

    # 尝试无密码连接到远程主机
    ssh -o PasswordAuthentication=no -o ConnectTimeout=10 $USERNAME@$IP exit
    if [ $? -ne 0 ]; then
      echo "无法无密码连接到 $IP. 需要密码。"
      if [ -z "$password" ]; then
        read -p "请输入你的主机密码: " -s password
        echo
      fi
      sshpass -p $password ssh -o ConnectTimeout=10 $USERNAME@$IP exit
      if [ $? -ne 0 ]; then
        echo "Unable to connect to $IP. Skipping."
        continue
      fi

      # 传送文件或目录
      sshpass -p $password scp -r $FILE ${USERNAME}@$IP:${DEST_PATH}/$FILE
    else
      # 传送文件或目录
      scp -r $FILE ${USERNAME}@$IP:${DEST_PATH}/$FILE
    fi

    if [ $? -eq 0 ]; then
      echo "Transfer of $FILE to $IP successful."
    else
      echo "Transfer of $FILE to $IP failed."
    fi
  done
done
